<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>优贷云 - AI助手群聊</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/layui/css/layui.css">
    <style>
        .layui-layout-admin .layui-body {
            bottom: 0;
            background: #343541;
        }

        .chat-container {
            height: calc(100vh - 180px);
            padding: 0;
            background: #343541;
            overflow-y: auto;
            color: #fff;
            margin-top: 40px;
            margin-right: 0;
            scroll-behavior: smooth;
            padding-bottom: 20px;
        }

        .message {
            padding: 8px 40px;
            display: flex;
            align-items: flex-start;
            border-bottom: none;
            animation: messageAppear 0.3s ease;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.ai-message {
            background: transparent;
            justify-content: flex-start;
            padding-right: 30%;
        }

        .message.user-message {
            background: transparent;
            justify-content: flex-end;
            padding-left: 30%;
        }

        .message.user-message .avatar {
            margin-right: 0;
            margin-left: 12px;
            order: 2;
        }

        .message.user-message .message-content {
            text-align: right;
            padding-right: 0;
            padding-left: 0;
        }

        .message.user-message .message-info {
            text-align: right;
        }

        .message-text {
            padding: 12px 16px;
            background: #f0f0f0;
            border-radius: 4px 16px 16px 16px;
            margin-top: 4px;
            display: inline-block;
            max-width: 100%;
            word-wrap: break-word;
            white-space: pre-wrap;
        }

        .message.user-message .message-text {
            background: #3498db;
            color: #fff;
            border-radius: 16px 4px 16px 16px;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 4px;
            margin-right: 12px;
            flex-shrink: 0;
        }

        .message-content {
            flex: 1;
            max-width: 100%;
            line-height: 1.6;
            font-size: 14px;
            color: #333;
            white-space: pre-wrap;
            padding-right: 0;
        }

        .message-info {
            font-size: 12px;
            color: rgba(255,255,255,0.7);
            margin-bottom: 4px;
        }

        .input-area {
            position: fixed;
            bottom: 0;
            left: 200px;
            right: 0;
            padding: 12px 40px;
            background: #343541;
            display: flex;
            align-items: flex-end;
            gap: 12px;
            border-top: 1px solid rgba(255,255,255,0.1);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .input-box {
            position: relative;
            flex: 1;
            max-width: 768px;
            margin: 0 auto;
            background: #40414f;
            border-radius: 12px;
            border: 1px solid rgba(255,255,255,0.1);
            padding: 0;
            min-height: 48px;
        }

        /* 使用原生textarea替换layui-textarea */
        .message-textarea {
            width: calc(100% - 62px);
            min-height: 24px;
            max-height: 150px;
            padding: 12px;
            background: transparent;
            border: none;
            outline: none;
            color: #fff;
            font-size: 14px;
            line-height: 1.5;
            resize: none;
            font-family: inherit;
            display: block;
        }

        .message-textarea:focus {
            outline: none;
            border: none;
        }

        .send-btn {
            position: absolute;
            right: 10px;
            bottom: 6px;
            width: 32px;
            height: 32px;
            padding: 0;
            background: transparent;
            border: none;
            color: rgba(255,255,255,0.6);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .send-btn:hover {
            color: #fff;
        }

        .send-btn:focus {
            outline: none;
        }

        .input-counter {
            position: absolute;
            right: 50px;
            bottom: 14px;
            font-size: 12px;
            color: rgba(255,255,255,0.3);
            pointer-events: none;
            user-select: none;
        }

        /* 系统消息样式 */
        .system-message {
            padding: 2px 120px;
            text-align: center;
            font-size: 12px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .system-message .message-content {
            background: rgba(255,255,255,0.05);
            color: rgba(255,255,255,0.7);
            margin: 2px auto;
            text-align: center;
            max-width: 280px;
            padding: 3px 10px;
            border-radius: 4px;
            box-shadow: none;
            border: 1px solid rgba(255,255,255,0.05);
            display: inline-flex;
            align-items: center;
            font-size: 10px;
            line-height: 1.2;
        }

        .system-message .message-content i {
            font-size: 10px;
            margin-right: 3px;
        }

        /* 不同类型的系统消息样式 */
        .system-message.connect .message-content {
            color: rgba(52, 211, 153, 0.8);  /* 成功绿色 */
            border-color: rgba(52, 211, 153, 0.2);
        }

        .system-message.disconnect .message-content {
            color: rgba(239, 68, 68, 0.8);   /* 错误红色 */
            border-color: rgba(239, 68, 68, 0.2);
        }

        /* 功能按钮区 */
        .function-area {
            position: fixed;
            left: 200px;
            top: 60px;
            right: 0;
            padding: 6px 120px;
            background: #343541;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            display: flex;
            gap: 8px;
            z-index: 1000;
            height: 36px;
            align-items: center;
        }

        .function-btn {
            padding: 4px 8px;
            background: transparent;
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 4px;
            color: rgba(255,255,255,0.8);
            font-size: 11px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            transition: all 0.2s;
            height: 24px;
            opacity: 0.8;
        }

        .function-btn:hover {
            background: rgba(255,255,255,0.1);
            color: #fff;
            opacity: 1;
        }

        .function-btn i {
            font-size: 14px;
        }

        /* 在线用户列表 */
        .online-users {
            position: fixed;
            left: 200px;
            top: 60px;
            width: 200px;
            background: #343541;
            border-right: 1px solid rgba(255,255,255,0.1);
            padding: 12px;
            color: #fff;
            height: calc(100vh - 60px);
            transition: all 0.3s ease;
            display: none;
            z-index: 999;
        }

        .online-users.show {
            display: block;
        }

        .online-title {
            font-weight: 500;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            color: rgba(255,255,255,0.8);
            font-size: 12px;
        }

        .user-list {
            list-style: none;
            padding: 0;
        }

        .user-item {
            display: flex;
            align-items: center;
            padding: 4px 6px;
            color: rgba(255,255,255,0.8);
            transition: all 0.2s;
            border-radius: 4px;
            font-size: 12px;
        }

        .user-item:hover {
            background: rgba(255,255,255,0.1);
        }

        .user-item img {
            width: 20px;
            height: 20px;
            border-radius: 2px;
            margin-right: 8px;
        }

        /* 滚动条美化 */
        .chat-container::-webkit-scrollbar {
            width: 3px;
        }

        .chat-container::-webkit-scrollbar-thumb {
            background: #565869;
            border-radius: 2px;
        }

        .chat-container::-webkit-scrollbar-track {
            background: transparent;
        }

        /* 添加新的布局容器 */
        .main-container {
            display: flex;
            height: calc(100vh - 60px);
            margin-left: 200px;
        }

        .chat-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
            padding-bottom: 80px;
        }

        .chat-section.with-users {
            margin-left: 200px;  /* 显示用户列表时留出空间 */
        }

        /* 添加显示/隐藏按钮样式 */
        .toggle-users-btn {
            padding: 4px 8px;
            background: transparent;
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 4px;
            color: rgba(255,255,255,0.8);
            font-size: 11px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            transition: all 0.2s;
            height: 24px;
            opacity: 0.8;
        }

        .toggle-users-btn:hover {
            background: rgba(255,255,255,0.1);
            color: #fff;
            opacity: 1;
        }

        .toggle-users-btn i {
            font-size: 14px;
        }

        /* 移除 layui 默认的表单样式 */
        .layui-form-item .layui-input-block {
            border: none !important;
            box-shadow: none !important;
        }

        .layui-form-item .layui-input:focus,
        .layui-form-item .layui-textarea:focus {
            border: none !important;
            box-shadow: none !important;
        }
    </style>
</head>

<body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">
        <!-- 头部区域 -->
        <div class="layui-header">
            <div class="layui-logo">优贷云 - AI助手群聊</div>
            {% include "back/templates/admin/common/header-user.html" %}
        </div>

        <!-- 左侧导航栏 -->
        {% include "back/templates/admin/common/menu.html" %}

        <!-- 内容主体区域 -->
        <div class="layui-body">
            <!-- 功能按钮区 -->
            <div class="function-area">
                <button class="function-btn" onclick="resetThread()">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置会话
                </button>
                <button class="function-btn" onclick="toggleTheme()">
                    <i class="layui-icon layui-icon-theme"></i>
                    深色模式
                </button>
                <button class="toggle-users-btn" onclick="toggleUserList()">
                    <i class="layui-icon layui-icon-group"></i>
                    在线用户
                </button>
            </div>

            <div class="main-container">
                <!-- 在线用户列表移动到左侧 -->
                <div class="online-users">
                    <div class="online-title">在线用户 (<span id="onlineCount">0</span>)</div>
                    <ul class="user-list" id="userList">
                        <!-- 在线用户将通过JavaScript动态添加 -->
                    </ul>
                </div>

                <!-- 聊天区域 -->
                <div class="chat-section">
                    <div class="chat-container" id="chatContainer">
                        <!-- 消息通过JavaScript动态添加 -->
                    </div>
                    
                    <div class="input-area">
                        <div class="input-box">
                            <textarea id="messageInput" placeholder="发送消息..." class="message-textarea" maxlength="2000"></textarea>
                            <div class="input-counter"><span id="charCount">0</span>/2000</div>
                            <button class="send-btn" onclick="sendMessage()" title="发送消息 (Enter)">
                                <i class="layui-icon layui-icon-release"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/admin/layui/layui.js"></script>
    <script>
        let ws;
        const chatContainer = document.getElementById('chatContainer');
        const messageInput = document.getElementById('messageInput');
        const userList = document.getElementById('userList');
        const onlineCount = document.getElementById('onlineCount');
        
        // 连接WebSocket
        function connectWebSocket() {
            ws = new WebSocket('ws://' + window.location.host + '/ws/chat/');
            
            ws.onopen = function() {
                console.log('WebSocket连接已建立');
                addSystemMessage('已连接到聊天室', 'connect');
            };
            
            ws.onmessage = function(event) {
                const data = JSON.parse(event.data);
                
                if (data.type === 'chat_message') {
                    addMessage(data.username, data.message, data.is_ai);
                } else if (data.type === 'user_list') {
                    updateUserList(data.users);
                }
            };
            
            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
                addSystemMessage('与聊天室的连接已断开', 'disconnect');
                // 尝试重新连接
                setTimeout(connectWebSocket, 3000);
            };
        }
        
        // 发送消息
        function sendMessage() {
            const message = messageInput.value.trim();
            if (message) {
                // 添加用户消息
                addMessage('我', message, false);
                
                // 重置输入框
                messageInput.value = '';
                messageInput.style.height = '24px';  // 使用新的默认高度
                charCount.textContent = '0';
                
                // 更新发送按钮状态
                const sendBtn = document.querySelector('.send-btn');
                sendBtn.style.color = 'rgba(255,255,255,0.6)';
                
                // 显示AI正在输入的状态
                const typingDiv = document.createElement('div');
                typingDiv.className = 'message ai-message';
                typingDiv.innerHTML = `
                    <img class="avatar" src="/media/default/AiChat.png">
                    <div class="message-content">
                        <div class="message-info">AI助手</div>
                        <div class="message-text">正在输入...</div>
                    </div>
                `;
                chatContainer.appendChild(typingDiv);
                scrollToBottom();

                // 模拟AI延迟回复
                setTimeout(() => {
                    // 移除正在输入状态
                    typingDiv.remove();
                    
                    // 随机选择一个回复
                    const randomResponse = mockResponses[Math.floor(Math.random() * mockResponses.length)];
                    
                    // 添加AI回复
                    addMessage('AI助手', randomResponse, true);
                }, 1500);
            }
        }
        
        // 添加消息到聊天界面
        function addMessage(username, message, isAi) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isAi ? 'ai-message' : 'user-message'}`;
            
            messageDiv.innerHTML = `
                <img class="avatar" src="${isAi ? '/media/default/AiChat.png' : '/media/default/UserImage.jpg'}">
                <div class="message-content">
                    <div class="message-info">${username}</div>
                    <div class="message-text">${message}</div>
                </div>
            `;
            
            chatContainer.appendChild(messageDiv);
            
            // 滚动到底部，使用 requestAnimationFrame 确在DOM更新后行
            requestAnimationFrame(() => {
                scrollToBottom();
            });
        }
        
        // 添加系统消息
        function addSystemMessage(message, type = 'normal') {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message system-message ${type}`;
            messageDiv.innerHTML = `
                <div class="message-content">
                    <i class="layui-icon ${type === 'connect' ? 'layui-icon-ok' : type === 'disconnect' ? 'layui-icon-close' : 'layui-icon-notice'}"></i>
                    ${message}
                </div>
            `;
            
            chatContainer.appendChild(messageDiv);
            scrollToBottom();

            // 5秒后淡出消息
            setTimeout(() => {
                messageDiv.style.opacity = '0';
                setTimeout(() => messageDiv.remove(), 300);
            }, 5000);
        }
        
        // 滚动到底部的函数
        function scrollToBottom() {
            requestAnimationFrame(() => {
                const scrollHeight = chatContainer.scrollHeight;
                chatContainer.scrollTo({
                    top: scrollHeight,
                    behavior: 'smooth'
                });
            });
        }
        
        // 监听输入框变化，自动调整高度
        messageInput.addEventListener('input', function() {
            // 更新字数统计
            const count = this.value.length;
            charCount.textContent = count;
            
            // 自动调整高度
            this.style.height = '24px';  // 先重置为默认高度
            const newHeight = Math.min(this.scrollHeight, 150);  // 限制最大高度
            this.style.height = newHeight + 'px';
            
            // 更新发送按钮状态
            const sendBtn = document.querySelector('.send-btn');
            sendBtn.style.color = count > 0 ? '#fff' : 'rgba(255,255,255,0.6)';
        });
        
        // 更新在线用户列表
        function updateUserList(users) {
            userList.innerHTML = '';
            onlineCount.textContent = users.length;
            
            users.forEach(user => {
                const li = document.createElement('li');
                li.className = 'user-item';
                li.innerHTML = `
                    <img src="/media/default/UserImage.jpg">
                    <span>${user.username}</span>
                `;
                userList.appendChild(li);
            });
        }
        
        // 监听Enter键发送消息
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 添加字数统计功能
        const charCount = document.getElementById('charCount');
        
        messageInput.addEventListener('input', function() {
            const count = this.value.length;
            charCount.textContent = count;
            
            // 根据是否有内容来切换发送按钮状态
            const sendBtn = document.querySelector('.send-btn');
            if (count > 0) {
                sendBtn.style.color = '#fff';
            } else {
                sendBtn.style.color = 'rgba(255,255,255,0.6)';
            }
        });
        
        // 添加切换用户列表的函数
        function toggleUserList() {
            const userList = document.querySelector('.online-users');
            const inputArea = document.querySelector('.input-area');
            
            if (userList.classList.contains('show')) {
                // 隐藏用户列表
                userList.classList.remove('show');
                inputArea.style.left = '200px';  // 恢复默认位置
            } else {
                // 显示用户列表
                userList.classList.add('show');
                inputArea.style.left = '400px';  // 左侧菜单(200px) + 用户列表(200px)
            }
        }

        // 页面加载完成后连接WebSocket
        window.onload = function() {
            // 连接WebSocket
            // connectWebSocket();  // 暂时注释掉WebSocket连接

            // 添加欢迎消息
            setTimeout(() => {
                addSystemMessage('欢迎来到AI助手群聊', 'connect');
            }, 500);

            setTimeout(() => {
                addMessage('AI助手', '您好！我是您的AI助手，请问有什么可以帮您？', true);
            }, 1000);

            // 初始化在线用户列表
            updateUserList();
        };

        // 模拟AI回复数据
        const mockResponses = [
            "您好！我是AI助手，很高兴为您服务。",
            "这是一个很好的问题。让我来为您解答...",
            "根据您的描述，我建议可以这样处理...",
            "我理解您的需求，从技术角度来看...",
            "这个问题比较复杂，让我分步骤为您分析：\n1. 首先...\n2. 其次...\n3. 最后...",
            "您说得对，不过我们还需要考虑以下几点...",
        ];

        // 模拟在线用户数据
        const mockUsers = [
            { username: '用户1', id: 1 },
            { username: '用户2', id: 2 },
            { username: '用户3', id: 3 }
        ];

        // 更新在线用户列表
        function updateUserList() {
            userList.innerHTML = '';
            onlineCount.textContent = mockUsers.length;
            
            mockUsers.forEach(user => {
                const li = document.createElement('li');
                li.className = 'user-item';
                li.innerHTML = `
                    <img src="/media/default/UserImage.jpg">
                    <span>${user.username}</span>
                `;
                userList.appendChild(li);
            });
        }

        // 初始化在线用户列表
        updateUserList();
    </script>
</body>
</html> 